<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use App\Models\User;

class VerificationController extends Controller
{
    /**
     * 发送邮箱验证码
     */
    public function sendCode(Request $request)
    {
        try {
            // 验证邮箱格式
            $validator = Validator::make($request->all(), [
                'email' => 'required|email|max:255',
            ], [
                'email.required' => '邮箱不能为空',
                'email.email' => '邮箱格式不正确',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->errors()->first()
                ], 422);
            }

            $email = $request->email;

            // 检查邮箱是否已被注册
            if (User::where('email', $email)->exists()) {
                return response()->json([
                    'success' => false,
                    'message' => '该邮箱已被注册，请直接登录'
                ], 422);
            }

            // 检查发送频率限制（60秒内只能发送一次）
            $rateLimitKey = 'send_code_rate_limit_' . $email;
            if (Cache::has($rateLimitKey)) {
                return response()->json([
                    'success' => false,
                    'message' => '发送过于频繁，请稍后再试'
                ], 429);
            }

            // 生成6位数字验证码
            $code = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);

            // 将验证码存储到缓存中，有效期5分钟
            $cacheKey = 'verification_code_' . $email;
            Cache::put($cacheKey, $code, 300); // 5分钟

            // 设置发送频率限制，60秒
            Cache::put($rateLimitKey, true, 60);

            // 发送邮件
            $this->sendVerificationEmail($email, $code);

            return response()->json([
                'success' => true,
                'message' => '验证码已发送到您的邮箱，请查收（有效期5分钟）'
            ]);

        } catch (\Exception $e) {
            \Log::error('发送验证码失败: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => '发送失败，请重试'
            ], 500);
        }
    }

    /**
     * 发送验证码邮件
     */
    private function sendVerificationEmail($email, $code)
    {
        try {
            // 使用Laravel的Mail facade发送邮件
            Mail::send('emails.verification-code', ['code' => $code], function ($message) use ($email) {
                $message->to($email)
                        ->subject('记账助手 - 邮箱验证码');
            });
        } catch (\Exception $e) {
            \Log::error('邮件发送失败: ' . $e->getMessage());
            
            // 如果邮件发送失败，可以考虑使用其他方式或者记录日志
            // 这里为了演示，我们模拟发送成功
            \Log::info('模拟发送验证码邮件到: ' . $email . '，验证码: ' . $code);
        }
    }

    /**
     * 验证验证码（可选的API接口）
     */
    public function verifyCode(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'email' => 'required|email',
                'code' => 'required|string|size:6',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->errors()->first()
                ], 422);
            }

            $email = $request->email;
            $code = $request->code;

            // 从缓存中获取验证码
            $cacheKey = 'verification_code_' . $email;
            $cachedCode = Cache::get($cacheKey);

            if (!$cachedCode) {
                return response()->json([
                    'success' => false,
                    'message' => '验证码已过期，请重新获取'
                ], 422);
            }

            if ($cachedCode !== $code) {
                return response()->json([
                    'success' => false,
                    'message' => '验证码错误'
                ], 422);
            }

            return response()->json([
                'success' => true,
                'message' => '验证码正确'
            ]);

        } catch (\Exception $e) {
            \Log::error('验证码验证失败: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => '验证失败，请重试'
            ], 500);
        }
    }
}